package service

import (
	response "api-gateway-engine/common"
	"api-gateway-engine/domain/model"
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"net/http"
)

// 注册网关信息
func DoRegister(address, groupId, gatewayId, gatewayName, gatewayAddress string) error {
	//1. 封装参数
	paramMap := make(map[string]string)
	paramMap["groupId"] = groupId
	paramMap["gatewayId"] = gatewayId
	paramMap["gatewayName"] = gatewayName
	paramMap["gatewayAddress"] = gatewayAddress
	data, err := json.Marshal(paramMap)
	if err != nil {
		return err
	}
	//2. 发送POST请求
	resp, err := http.Post(address+"/wg/admin/config/registerGateway", "application/json;charset=utf-8", bytes.NewBuffer(data))
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	//3. 解析结果
	data, err = io.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var result response.Response[bool]
	err = json.Unmarshal(data, &result)
	if err != nil {
		return err
	}
	//4. 判断返回结果
	if "0000" != result.Code {
		return errors.New("网关服务注册异常 [gatewayId：" + gatewayId + "] 、[gatewayAddress：" + gatewayAddress + "]")
	}
	return nil
}

// 从网关中心拉取配置
func PullApplicationSystemRichInfo(address, gatewayId, systemId string) (*model.ApplicationSystemRichInfo, error) {
	//1. 发送GET请求
	resp, err := http.Get(address + "/wg/admin/config/queryApplicationSystemRichInfo?gatewayId=" + gatewayId + "&systemId=" + systemId)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	//2. 解析结果
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	var result response.Response[*model.ApplicationSystemRichInfo]
	err = json.Unmarshal(data, &result)
	if err != nil {
		return nil, err
	}
	//3. 判断返回结果
	if "0000" != result.Code {
		return nil, errors.New("从网关中心拉取应用服务和接口的配置信息到本地完成注册异常 [gatewayId：" + gatewayId + "]")
	}
	return result.Data, nil
}
